/**
 * Created by Administrator on 2017/6/30.
 * declare:本例使用bootstrapvalidation进行表单校验
 */
define(['knockout', 'platform.common', 'bootbox', 'knockout-bsTable', 'knockout-jsTree', 'knockout-component', 'bootstrapValidator', 'bootstrapValidator-zhCN',
    'sco.msg'], function (ko, platform, bootbox) {

    /**
     *
     * @type {{get: get, remove: remove, save: save, grantMenu: grantMenu, grantUser: grantUser, grantPerm: grantPerm, repeatCheck: repeatCheck}}
     */
    var rest = {
        get: function (id) {
            var param = {};
            param.role_id = id;
            var result = platform.servicebreak('~/rest/role/selectOne', param).responseJSON;
            return result;
        },
        remove: function (id) {
            var param = {};
            param.role_id = id;
            platform.servicebreakAsync('~/rest/role/delete', param, 'post')
                .done(function (response) {
                    if (response instanceof Object && response.meta.success) {
                        platform.showOperTip('DELSUC');
                        viewModel.tableViewModel.refresh();
                    }
                });
        },
        save: function (param) {
            platform.servicebreakAsync('~/rest/role/save', param, 'post',
                function () {
                    platform.showOperTip('dealing');
                }).done(function (response) {
                if (response instanceof Object && response.meta.success) {
                    platform.showOperTip('savesuc');
                    viewModel.tableViewModel.refresh();
                }
            });
        },
        grantMenu: function (param) {
            platform.servicebreakAsync('~/rest/role/grantMenuToRole', param,
                'post').done(function (response) {
                if (response instanceof Object && response.meta.success) {
                    platform.showOperTip('GRANTSUC');
                }
            });
        },
        grantUser: function (param) {
            platform.servicebreakAsync('~/rest/role/grantRoleToUser', param,
                'post').done(function (response) {
                if (response instanceof Object && response.meta.success) {
                    platform.showOperTip('GRANTSUC');
                }
            });
        },
        grantPerm: function (param) {
            platform.servicebreakAsync('~/rest/role/grantPermToRole', param,
                'post').done(function (response) {
                if (response instanceof Object && response.meta.success) {
                    platform.showOperTip('GRANTSUC');
                }
            });
        },
        repeatCheck: function (code) {
            var param = {};
            param.role_code = roleCode;
            var result = platform.servicebreak('~/rest/role/repeatCheck', param).responseJSON;
            return result;
        }
    };
    var kbTable = require('knockout-bsTable');
    // var jsTree = require('knockout-jsTree');

    var ViewModel = function () {
        var self = this;
        self.columns = [
            {
                checkbox: true,
                field: 'checkbox',
                align: 'center',
                width: 30
            },
            {
                field: 'display_order',
                title: '序号',
                formatter: function (value, row, index) {
                    var options = self.tableViewModel.getOptions();
                    var indexPageNum = parseInt(options.pageNumber);
                    var indexPageSize = parseInt(options.pageSize);
                    return ((indexPageNum - 1) * indexPageSize)
                        + (index + 1);
                },
                width: 35,
                align: 'center'
            },
            {
                field: 'role_id',
                title: '主键标识',
                width: 250,
                align: 'center',
                visible: false
            },
            {
                field: 'role_name',
                title: '角色名称',
                width: 120
            },
            {
                field: 'role_code',
                title: '角色编码',
                width: 200
            },
            {
                field: 'def_uri',
                title: '默认主页地址'
            }];
        //dialog 显示控制器
        self.modalVisible = ko.observable(false);
        self.grantmenuModalVisible = ko.observable(false);
        self.grantUserModalVisible = ko.observable(false);
        self.grantPermModalVisible = ko.observable(false);

        self.tableViewModel = new kbTable.bootstrapTableViewModel({
            url: platform.mapUrl('~/rest/role/list'),
            toolbar: '#toolbar',
            queryParams: function (params) {
                return {
                    pageNumber: params.offset / params.limit + 1,
                    pageSize: params.limit
                };
            },
            columns: self.columns
        });
        self.roleViewModel = {
            title: ko.observable(),
            roleId: ko.observable(),// 角色ID
            roleCode: ko.observable(),// 角色编码
            roleName: ko.observable(), // 角色名称
            roleGroupId: ko.observable(), // 角色组，暂未实现20170320
            defUri: ko.observable(), // 默认首页
            editStatus: ko.observable(), // 默认数据状态
            recordStatus: ko.observable(), // 默认数据状态
            enabled: ko.observable(false), // 只读设置
            resetForm: function () {
                $('#detailForm').resetForm();

                if ($('#detailForm').data('bootstrapValidator') != null ||
                    $('#detailForm').data('bootstrapValidator') != undefined) {
                    $('#detailForm').data('bootstrapValidator').resetForm();
                }

                this.title('');
                this.roleId('');
                this.roleCode('');
                this.roleName('');
                this.roleGroupId('');
                this.defUri('');
                this.editStatus('');
                this.recordStatus('');
                this.enabled(true);
            },
            disableForm: function () {
                $('#detailForm').find('input,textarea').attr('disabled', true);
            },
            enableForm: function () {
                $('#detailForm').find('input,textarea').attr('disabled', false);
            },
            setFormData: function (id) {
                var result = rest.get(id);
                if (result instanceof Object && result.meta.success) {
                    var info = result.responseObject;
                    this.roleId(info.role_id);
                    this.roleCode(info.role_code);
                    this.roleName(info.role_name);
                    this.roleGroupId(info.role_group_id);
                    this.defUri(info.def_uri);
                    this.editStatus(info.edit_status);
                    this.recordStatus(info.record_status);
                }
            },
            validateForm: function () {
                $('#detailForm').bootstrapValidator({
                    message: 'This value is not valid',
                    feedbackIcons: {
                        valid: 'glyphicon glyphicon-ok',
                        invalid: 'glyphicon glyphicon-remove',
                        validating: 'glyphicon glyphicon-refresh'
                    },
                    excluded: [':disabled'],
                    fields: {
                        roleName: {
                            validators: {
                                notEmpty: {
                                    message: '角色名称为必填字段,不可为空'
                                }
                            }
                        },
                        roleCode: {
                            validators: {
                                notEmpty: {
                                    message: '角色编码为必填字段,不可为空'
                                }
                            }
                        }
                    }
                });
            },
            showNewForm: function () {
                this.resetForm();
                this.validateForm();
                this.enableForm();

                this.title('新增角色信息');
                this.roleId(platform.uuid());
                this.editStatus('0');
                this.recordStatus('1');
                self.modalVisible(true);
            },
            showEditForm: function (id) {
                this.resetForm();
                this.validateForm();
                this.enableForm();

                this.title('编辑角色信息');
                this.setFormData(id);
                self.modalVisible(true);
            },
            showViewForm: function (id) {
                this.resetForm();
                this.disableForm();

                this.title('查看角色信息');
                this.enabled(false);
                this.setFormData(id);
                self.modalVisible(true);
            },
            save: function () {
                $('#detailForm').data('bootstrapValidator').validate();
                if (!$('#detailForm').data('bootstrapValidator').isValid()) {
                    platform.showOperTip('VALIDATEFAIL');
                    return;
                }

                var param = {};
                param.role_id = this.roleId();
                param.role_name = this.roleName();
                param.role_code = this.roleCode();
                param.edit_status = this.editStatus();
                param.record_status = this.recordStatus();

                var result = rest.repeatCheck(param.role_code);

                if (result.statusCode) {
                    rest.save(param);

                } else {
                    platform.showErrorTip(result.msg);

                }
            },
            close: function () {
                self.modalVisible(false);
                $('#roleDialog').toggleClass('hide');
            }
        };
        self.grantMenuViewModel = {
            title: ko.observable(),
            roleId: ko.observable(),
            init: function (roleId) {
                $('#grantMenuTree').jstree({
                    core: {
                        data: {
                            url: platform.mapUrl('~/rest/role/getMenusByRoleId'),
                            data: function () {
                                return JSON.stringify({'role_id': roleId});
                            },
                            contentType: 'application/json',
                            dataType: 'json',
                            method: 'post'
                        }
                    },
                    check_callback: true,
                    checkbox: {'keep_selected_style': false, "three_state": false, "tie_selection": true},
                    plugins: ['wholerow', 'checkbox']
                })
            },
            distribute: function () {
                var param = {};
                param.role_id = this.roleId();
                var selectedNode = $('#grantMenuTree').jstree(true).get_checked();
                param.menu_id = [];
                $.each(selectedNode, function (index, node) {
                    param.menu_id.push(node);
                });
                rest.grantMenu(param);
            },
            close: function () {
                self.grantmenuModalVisible(false);
                $('#grantMenuDialog').toggleClass('hide');
            }
        };
        self.grantUserViewModel = {//组织机构人员树
            title: ko.observable(),
            roleId: ko.observable(),
            // tableViewModel: new kbTable.bootstrapTableViewModel(),
            init: function (roleId) {//initial function
                $('#grantUserTree').jstree({
                    core: {
                        data: {
                            url: platform.mapUrl('~/rest/role/getUsersByRoleId'),
                            data: function () {
                                return JSON.stringify({'role_id': roleId});
                            },
                            contentType: 'application/json',
                            dataType: 'json',
                            method: 'post'
                        }
                    },
                    check_callback: true,
                    checkbox: {'keep_selected_style': false, "three_state": false, "tie_selection": true},
                    plugins: ['wholerow', 'checkbox']
                })
            },
            distribute: function () {
                var param = {};
                param.role_id = this.roleId();
                param.user_id = [];
                var selectedNode = $('#grantUserTree').jstree(true).get_checked(true);
                $.each(selectedNode, function (index, node) {
                    if (node.original.attributes.type === 'USER') {
                        param.user_id.push(node.id);
                    }
                });
                rest.grantUser(param);
            },
            close: function () {
                self.grantUserModalVisible(false);
                $('#grantUserDialog').toggleClass('hide');
            }
        };
        self.grantPermViewModel = {};
        self.grantPermViewModel.title = ko.observable();
        self.grantPermViewModel.roleId = ko.observable();
        self.grantPermViewModel.init = function (roleId) {
            $('#grantPermTree').jstree({
                core: {
                    data: {
                        url: platform.mapUrl('~/rest/role/getPermsByRoleId'),
                        data: function () {
                            return JSON.stringify({'role_id': roleId});
                        },
                        contentType: 'application/json',
                        dataType: 'json',
                        method: 'post'
                    }
                },
                check_callback: true,
                checkbox: {'keep_selected_style': false, "three_state": false, "tie_selection": true},
                plugins: ['wholerow', 'checkbox']
            })
        };
        self.grantPermViewModel.distribute = function () {
            var param = {};
            param.role_id = this.roleId();
            rest.grantPerm(param);
        };
        self.grantPermViewModel.close = function () {
            self.grantPermModalVisible(false);
            $('#grantPermDialog').toggleClass('hide');
        };
        /**
         * method definition
         */
        self.fnSearch = function () {

        };
        self.fnAdd = function () {
            self.roleViewModel.showNewForm();
            $('#roleDialog').toggleClass('hide');
        };
        self.fnRemove = function () {
            var selections = self.tableViewModel.getSelections();
            if (selections.length == 1) {
                bootbox.confirm({
                    title: '删除提示',
                    size: 'small',
                    message: '是否删除该节点数据?',
                    buttons: {
                        confirm: {
                            label: '确认',
                            className: 'btn-success btn-sm'
                        },
                        cancel: {
                            label: '取消',
                            className: 'btn-default btn-sm'
                        }
                    },
                    callback: function (result) {
                        if (result) {
                            rest.remove(selections[0].role_id);
                        }
                    }
                });
            } else {
                platform.showTip('REMOVE');

            }
        };
        self.fnEdit = function () {
            var selections = self.tableViewModel.getSelections();
            if (selections.length == 1) {
                self.roleViewModel.showEditForm(selections[0].role_id);
                $('#roleDialog').toggleClass('hide');
            } else {
                platform.showTip('EDIT');

            }
        };
        self.fnView = function () {
            var selections = self.tableViewModel.getSelections();
            if (selections.length == 1) {
                self.roleViewModel.showViewForm(selections[0].role_id);
                $('#roleDialog').toggleClass('hide');
            } else {
                platform.showTip('VIEW');

            }
        };
        self.fnGrantMenu = function () {
            var selections = self.tableViewModel.getSelections();
            if (selections.length == 1) {
                self.grantMenuViewModel.title('选择菜单');
                self.grantMenuViewModel.roleId(selections[0].role_id);
                self.grantMenuViewModel.init(selections[0].role_id);
                self.grantmenuModalVisible(true);
                $('#grantMenuDialog').toggleClass('hide');
            } else {
                platform.showTip('GRANT');

            }
        };
        self.fnGrantUser = function () {
            var selections = self.tableViewModel.getSelections();
            if (selections.length == 1) {
                self.grantUserViewModel.title('选择人员');
                self.grantUserViewModel.roleId(selections[0].role_id);
                self.grantUserViewModel.init(selections[0].role_id);
                self.grantUserModalVisible(true);
                $('#grantUserDialog').toggleClass('hide');
            } else {
                platform.showTip('GRANT');

            }
        };
        self.fnGrantPerm = function () {
            var selections = self.tableViewModel.getSelections();
            if (selections.length == 1) {
                self.grantPermViewModel.title('选择权限');
                self.grantPermViewModel.roleId(selections[0].role_id);
                self.grantPermViewModel.init(selections[0].role_id);
                self.grantPermModalVisible(true);
                $('#grantPermDialog').toggleClass('hide');
            } else {
                platform.showTip('GRANT');

            }
        }
    };
    var viewModel = new ViewModel();
    return viewModel;
});